package cn.leaf.calculator.old;

import cn.hutool.script.ScriptUtil;

import cn.leaf.calculator.test.TestEntity;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import javax.script.ScriptException;
import java.util.List;
import java.util.Objects;

/**
 * TODO
 *
 * @author 李克国
 * @version 1.0.0

 */
public class SimpleCalHelperImpl extends CalHelper<TestEntity> {
    public SimpleCalHelperImpl(List<TestEntity> calList) {
        super(calList);
    }

    @Override
    protected CalUnit<TestEntity> buildCalUnit(TestEntity entity) {
        CalUnit<TestEntity> calUnit = new CalUnit<TestEntity>(entity.getKey(), entity);
        calUnit.setFormulaString(entity.getFormula());
        return calUnit;
    }

    @Override
    protected void cal(CalUnit<TestEntity> currentCalUnit, List<CalUnit<TestEntity>> referencedArgs) {

        CalFormula formula = new CalFormula(currentCalUnit.getFormulaScript().getFormula());
        TestEntity entity = currentCalUnit.getEntity();
        ExpressionParser ep = new SpelExpressionParser();
        // 创建上下文变量
        EvaluationContext ctx = new StandardEvaluationContext();
        referencedArgs.forEach(p -> ctx.setVariable(p.getFormulaId(), p.getEntity().getValue()));
        Object value = ep.parseExpression(formula.getFormula(), new TemplateParserContext()).getValue(ctx);
        Object eval = null;
        try {
            eval = ScriptUtil.getJavaScriptEngine().eval(Objects.requireNonNull(value).toString());
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        assert eval != null;
        entity.setValue(Integer.parseInt(eval.toString()));
    }

    @Override
    protected void calOkBefore(TestEntity entity) {

    }
}
